<template>
  <div>
    <el-button v-if="url" link type="primary" size="small" @click="handleOpen">
      电子回单
    </el-button>
    <el-dialog v-model="dialogVisible" :title="title || '电子回单预览'" width="800px" :align-center="true">
      <div class="preview-container" style="text-align: center;">
        <el-image
          v-if="url"
          :src="url"
          :preview-src-list="[url]"
          alt="电子回单"
          style="max-width: 100%; max-height: 500px; margin: 0 auto;"
          fit="contain"
        />
        <p v-else style="color: #999;">暂无图片</p>
      </div>

      <template #footer>
        <div class="dialog-footer">
         
          <el-button v-if="url" type="primary" @click="downloadImage">
            下 载
          </el-button>
           <el-button @click="dialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, PropType } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  url: {
    type: String as PropType<string | null>,
    default: null,
  },
  title: {
    type: String,
    default: undefined,
  },
})

const dialogVisible = ref(false)

const handleOpen = () => {
  if (!props.url) {
    ElMessage.warning('该记录暂无电子回单')
    return
  }
  dialogVisible.value = true
}

const downloadImage = () => {
  if (!props.url) return
  const link = document.createElement('a')
  link.href = props.url
  const filename = decodeURIComponent(props.url.split('/').pop() || 'receipt.jpg')
  link.setAttribute('download', filename)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('下载中，请注意浏览器下载提示')
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
.preview-container {
  min-height: 200px;
}
</style>